using Ccdk.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Ccdk.Data;
using Ccdk.Dto;
namespace Ccdk.Controllers.ProductController;

[ApiController]
[Route("api/[controller]")]
public class ProductController : ControllerBase
{
    private readonly MyDbContext _db;
    public ProductController(MyDbContext db) => _db = db;

    [HttpGet]
    public async Task<IActionResult> Get() 
    {
        var products = await _db.Products.ToListAsync();
        var res=new{Code=1000,Data=products,Msg="获取列表成功"};
        return Ok(res);
    }
    [HttpPost]
    public IActionResult Post(ProductCreateDto productCreateDto){
        var product=new Product{Name=productCreateDto.Name,Price=productCreateDto.Price};
        var obj=_db.Products.Add(product).Entity;
        _db.SaveChanges();
        var objConvert= new ProductResultDto(obj.Name,obj.Price);
        var res=new{Code=1000,Data=objConvert,Msg="新增成功"};
        return Ok(res);
    }
}

